<template>
    <div>
      <el-dialog v-model="model" :title="type=='ADD'?'添加菜单':'编辑菜单'" width="500" :close-on-click-modal="false">
        <template #default>
            <el-dialog v-model="menuTreeModal" width="30%" title="请选择上级菜单" append-to-body :close-on-click-modal="false">
                <menuTree @handleNodeClickEmit = "chooseParent"/>
                <template #footer>
                    <el-button @click="closeChooseMenu">取消</el-button>
                    <el-button type="primary" @click="comfirmChooseMenu">确定</el-button>
                </template>
            </el-dialog>
            <el-form :model="form" label-width="80" :rules="rules" ref="formRef">
              <el-form-item label="上级菜单" prop="parent_id">
                <el-button type="primary" @click="openChooseMenu">选择上级菜单</el-button><span class="M-L-5">{{ parentLabel }}</span>
              </el-form-item>
              <el-form-item label="菜单名称" prop="title">
                <el-input v-model="form.title" />
              </el-form-item>
              <el-form-item label="路由" prop="route_name">
                <el-input v-model="form.route_name" />
              </el-form-item>
              <el-form-item label="请求API" prop="api_route_name">
                <el-input v-model="form.api_route_name" />
              </el-form-item>
              <el-form-item label="类型" prop="type">
                <el-select v-model="form.type" placeholder="选择菜单类型">
                  <el-option v-for="(item,index) in typeDrop" :key="index" :value="item.Value" :label="item.Key"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="是否启用">
                  <el-option v-for="(item,index) in statusDrop" :key="index" :value="item.Value" :label="item.Key"></el-option>
                </el-select>
              </el-form-item>
        </el-form>
        </template>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="submitForm(formRef)">
              {{type=='ADD'?'添加':'修改'}}
            </el-button>
          </span>
        </template>
        
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts">
  import router from '@/router'
  import { moduleExpression } from '@babel/types'
  import menuEnums from '@/config/Enums/menu'
  import Pinterface from '@/config/Interface/Public'
  import Interface from '@/config/Interface/Menu'
  import { defineComponent,ref,onMounted,reactive,toRefs} from 'vue'
  import { getCurrentInstance} from 'vue'
  import { useStore } from '../../store'
  import { ElMessage, FormInstance, FormRules } from 'element-plus'
  import {findMenuApi,createMenuApi,updateMenuApi,deleteMenuApi} from '@/request/menu'

  import menuTree from '@/components/menu/menuTree.vue'
 
  export default defineComponent({
    name: 'addUser',
    components: {
        menuTree
    },
    setup(props,{ emit }){
      const store = useStore()
      const context = getCurrentInstance()?.appContext.config.globalProperties; //获取this
      const msg = reactive<any>({})
      const model =ref(false) // 模态框显示隐藏
      const menuTreeModal =ref(false) // 模态框显示隐藏
      const type = ref('') //类型 添加/编辑
        
      const chooseMenuRef = ref()
      const reactiveData = reactive<Interface.addMenuReactiveData>({
        form:{
          parent_id:'',
          title:'',
          route_name:'',
          api_route_name:'',
          type:'',
          status:'',
        },
        statusDrop:context?.$enums.GetEnumArr(menuEnums.StatusDrop),
        typeDrop:context?.$enums.GetEnumArr(menuEnums.TypeDrop),
      })
  
      const pidToName:any = async (parent_id:any) =>{
        if(parent_id === 0) {
            parentLabel.value = '资源菜单'
        }else {
            const res = await findMenuApi({id:Number(parent_id)})
            if(res.data.code ===1){
                parentLabel.value = res.data.data.title
            }
        }
        
      }

      const trigger = (Type:string,scope?:any) =>{
        model.value = true
        type.value = Type
        if(scope) {
          msg.value = scope.row
          pidToName(msg.value.parent_id)
          reactiveData.form.parent_id = msg.value.parent_id
          reactiveData.form.title = msg.value.title
          reactiveData.form.route_name = msg.value.route_name
          reactiveData.form.api_route_name = msg.value.api_route_name
          reactiveData.form.status = msg.value.status
          reactiveData.form.type = msg.value.type
        }
      }
      
  
  
      
      const checkParent = (rule: any, value: any, callback: any) => {
          if(value===''){
            return callback(new Error('请选择资源菜单'))
          }else{
            callback()
          }
      }
      const rules = reactive<FormRules>({
        parent_id:[
          { required: true, validator: checkParent, trigger: 'blur' },
        ],
        title:[
          { required: true, message: '请输入菜单名称', trigger: 'blur' },
        ],
        route_name:[
        ],
        api_route_name:[
          { required: true, message: '请输入请求API', trigger: 'blur' },
        ],
        type:[
          { required: true, message: '请选择类型', trigger: 'change' },
        ],
        status:[
          { required: true, message: '请选择状态', trigger: 'change' },
        ],
      })
      // 关闭表单
      const close = () => {
        reactiveData.form = new Interface.addMenuForm()
        model.value = false;
      }
      const formRef = ref<FormInstance>()
      // 提交表单
      const submitForm = async (formEl: FormInstance | undefined) => {
        if (!formEl) {
          return
        }else{
          await formEl.validate((valid, fields) => {
          console.log(valid);
          if (!valid) {
            return
          } else {
            postSend()
          }
        })
        }
      }
  
      const postSend = async () =>{
        const postData:any = {
          ...reactiveData.form,
        }
        if(type.value =='ADD'){
            console.log(1);
            
          const res = await createMenuApi(postData)
          if(res.data.code === 1){
            ElMessage({
              message:"创建成功",
              type:"success"
            })
            close()
            emit('RefreshListEmit')
          }
        }else{
          postData.id = msg.value.id
          const res = await updateMenuApi(postData)
          if(res.data.code === 1){
            ElMessage({
              message:"修改成功",
              type:"success"
            })
            close()
            emit('RefreshListEmit')
          }
        }
      }

      // 打开选择菜单模态框
      const openChooseMenu = () => {
        menuTreeModal.value = true
      }

      const parentName = ref('')
      const parentLabel = ref('')
      // 选择父节点
      const chooseParent = (data:any,tableData:any) => {
        reactiveData.form.parent_id = data.id
        parentName.value = data.label
      }

      const closeChooseMenu = () => {
        menuTreeModal.value = false
      }
      const comfirmChooseMenu = () => {
        parentLabel.value = parentName.value
        closeChooseMenu()
      }
  
      return {
        ...toRefs(reactiveData),
        model,type,menuTreeModal,
        trigger,
        rules,
        submitForm,
        close,formRef,openChooseMenu,chooseParent,
        closeChooseMenu,comfirmChooseMenu,parentLabel

      }
    }
  })
  </script>
  
  <style scoped lang="stylus">
  </style>
  